package model

import (
	"context"
	myErr "goHelpers/app/error"

	"gitee.com/copylian/lian-go.git/bootstrap"
	"gorm.io/gorm"
)

// MysqlClient mysql连接对象
type MysqlClient struct {
	DB *gorm.DB
}

// NewMysqlClient 返回mysql客户端连接实例
func NewMysqlClient(ctx context.Context, name string) *MysqlClient {
	client := &MysqlClient{}
	db, err := client.WithDBContext(ctx, name) //gdb.GetMysqlInstance(name)

	// 验证记录数据库错误
	CheckMysqlError(err)

	// 返回
	client.DB = db
	return client
}

// WithDBContext 获取数据库连接实例
func (mc MysqlClient) WithDBContext(ctx context.Context, name string) (*gorm.DB, error) {
	instance, err := bootstrap.GetMysqlInstance(name)
	if err != nil {
		return nil, err
	}
	return instance.DB, nil
}

// CheckMysqlError 验证数据库错误
func CheckMysqlError(err error) myErr.Error {
	if err == nil || err == gorm.ErrRecordNotFound {
		return nil
	}
	e := myErr.NewError("mysql")
	e.AppendCause().SetCause(err)
	e.SetMessage(err.Error())

	// 记录错误
	bootstrap.CheckError(e, "mysql")

	// 返回
	return e
}
